package ch.fhnw.qualiscan.core.helpers;

import java.util.Date;
import java.util.List;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.models.SurveyModel;
import ch.fhnw.qualiscan.application.models.UserModel;
import ch.fhnw.qualiscan.core.db.pojos.Stage;
import ch.fhnw.qualiscan.core.db.pojos.StageText;
import ch.fhnw.qualiscan.core.db.pojos.Survey;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.db.pojos.User;

public class StageHelper {
	
	private SurveyModel surveyModel;
	private SessionHelper sessionHelper;
	private UserModel userModel;
	private User user;
	
	public StageHelper() {
		surveyModel = new SurveyModel();
		userModel = new UserModel();
		sessionHelper = new SessionHelper();
		user = new User();
		user.setId(sessionHelper.getUserSession().getId());
	}
	
	public StageText getStageText(Stage stage) {
		StageText stageText = surveyModel.getStageText(stage, sessionHelper.getUserSession().getLanguage());
		return stageText;
	}
	
	public StageText getNextStageText(Stage stage) {
		StageText nextStageText = surveyModel.getStageText(getNextStage(stage), sessionHelper.getUserSession().getLanguage());
		return nextStageText;
	}
	
	public Stage getNextStage(Stage stage) {
		Stage nextStage = surveyModel.getNextStage(stage);
		return nextStage;
	}
	
	public void nextStage(Survey survey) {
		if (changeNextStage(survey)) {
			if (survey.getStage().getId() == Config.STAGE_SURVEY) {
				//Change to STAGE_EVALUTATION
				
				//Delete User from SurveyUserRole without complete answers
				List<SurveyUserRole> surList = userModel.getUsersNotCompleted(survey, user);
				for (int a = 0; a < surList.size(); a++) {
					surveyModel.removeUserFromSurvey(surList.get(a));
				}
			}
			if (survey.getStage().getId() == Config.STAGE_EVALUATION) {
				//Change to STAGE_COMPLETED
			}

			surveyModel.changeToNextStage(survey.getStage(), survey);
		}
	}
	
	public boolean changeNextStage(Survey survey) {
		if (surveyModel.isNextStage(survey.getStage())) {
			Date now = new java.util.Date();
			if (now.compareTo(survey.getCompletiondate()) == 0 || now.compareTo(survey.getCompletiondate()) > 0) {
				return true;
			}
		}
		return false;
	}
	
	public boolean isNextStage(Stage stage) {
		return surveyModel.isNextStage(stage);
	}
	
	public int getState(Survey survey) {
		
		if(survey.getStage().getId() == Config.STAGE_SURVEY) {
			
			if(!changeNextStage(survey)) {
				return 1;
			} else {
				return 2;
			}
			
		}
		
		if(survey.getStage().getId() == Config.STAGE_EVALUATION) {
			return 3;
		}
		if (survey.getStage().getId() == Config.STAGE_COMPLETED) {
			return 4;
		}
		
		return -1;
	}
	
}
